using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using QFramework.Framework.Util;
using UnityEngine;
using UnityEngine.Networking;

namespace QFramework.Framework.ResKit.HotUpdate
{
    [Serializable]
    public class ResVersion
    {
        public int version;

        public List<string> assetBundleNames = new();
    }

    /// <summary>
    ///     模拟资源服务器
    /// </summary>
    public class FakeResServer : MonoSingleton<FakeResServer>
    {
        public static string TempAssetBundlesPath => Application.persistentDataPath + "/TempAssetBundles";

        public void GetRemoteResVersion(Action<int> onRemoteResVersionGet)
        {
            StartCoroutine(HotUpdateMgr.Instance.Config.RequestRemoteResVersion(resVersion =>
                onRemoteResVersionGet(resVersion.version)));
        }

        public void DownloadRes(Action downloadDone)
        {
            // 请求 远程的资源信息
            StartCoroutine(HotUpdateMgr.Instance.Config.RequestRemoteResVersion(remoteResVersion =>
            {
                // 开始逐个下载
                StartCoroutine(DoDownloadRes(remoteResVersion, downloadDone));
            }));
        }

        private IEnumerator DoDownloadRes(ResVersion remoteResVersion, Action downloadDone)
        {
            // 创建临时目录
            if (!Directory.Exists(TempAssetBundlesPath)) Directory.CreateDirectory(TempAssetBundlesPath);

            // 保存 ResVersion.json 文件
            var tempResVersionFilePath = TempAssetBundlesPath + "/ResVersion.json";
            var tempResVersionJson = JsonUtility.ToJson(remoteResVersion);
            File.WriteAllText(tempResVersionFilePath, tempResVersionJson);

            var remoteBasePath = HotUpdateMgr.Instance.Config.RemoteAssetBundlesURLBase;

            // 补上 AssetBundleManifest 文件 比如：Windows
            remoteResVersion.assetBundleNames.Add(ResKitUtil.GetPlatformName());

            foreach (var assetBundleName in remoteResVersion.assetBundleNames)
            {
                var www = new UnityWebRequest(remoteBasePath + assetBundleName);
                www.downloadHandler = new DownloadHandlerBuffer();

                www.SendWebRequest();
                yield return null;

                var bytes = www.downloadHandler.data;

                var filePath = TempAssetBundlesPath + "/" + assetBundleName;
                File.WriteAllBytes(filePath, bytes);
            }

            downloadDone();
        }
    }
}